// pages/admin/notice/notice.js
const app = getApp();

Page({
  data: {
    noticeList: [],
    isLoading: true,
    activeTab: 'all',
    page: 1,
    limit: 10,
    hasMore: true,
    errorMsg: ''
  },

  onLoad: function() {
    console.log('管理员通知页面加载');
    this.loadNoticeList(true);
  },

  onShow: function() {
    // 每次页面显示时刷新通知列表
    console.log('管理员通知页面显示');
    this.loadNoticeList(true);
  },

  onPullDownRefresh: function() {
    this.loadNoticeList(true).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadNoticeList(false);
    }
  },

  // 切换标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    console.log('切换标签:', tab);
    this.setData({ 
      activeTab: tab,
      page: 1,
      noticeList: [],
      hasMore: true
    });
    this.loadNoticeList(true);
  },

  // 加载通知列表
  loadNoticeList: function(refresh = false) {
    if (this.data.isLoading && !refresh) {
      return Promise.resolve();
    }
    
    this.setData({ 
      isLoading: true,
      errorMsg: '',
      page: refresh ? 1 : this.data.page
    });
    
    // 如果是刷新，清空列表
    if (refresh) {
      this.setData({
        noticeList: [],
        hasMore: true
      });
    }
    
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    console.log('请求通知列表, URL:', `${serverUrl}/api/admin/notices`);
    
    return new Promise((resolve) => {
      wx.request({
        url: `${serverUrl}/api/admin/notices`,
        method: 'GET',
        data: {
          page: this.data.page,
          limit: this.data.limit,
          type: this.data.activeTab !== 'all' ? this.data.activeTab : ''
        },
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          console.log('获取通知响应:', res);
          
          if (res.statusCode === 200) {
            // 从响应中提取notices数组
            let newNotices = [];
            
            if (res.data && res.data.notices && Array.isArray(res.data.notices)) {
              newNotices = res.data.notices;
              console.log('成功获取通知列表:', newNotices);
            } else if (Array.isArray(res.data)) {
              newNotices = res.data;
              console.log('成功获取通知列表(数组格式):', newNotices);
            } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
              newNotices = res.data.data;
              console.log('成功获取通知列表(data字段):', newNotices);
            } else {
              console.error('无法解析通知数据:', res.data);
            }
            
            // 处理分页信息
            let hasMore = true;
            if (res.data && res.data.pagination) {
              hasMore = res.data.pagination.page < res.data.pagination.pages;
              console.log('分页信息:', res.data.pagination, '是否有更多:', hasMore);
            } else {
              hasMore = newNotices.length === this.data.limit;
            }
            
            // 安全地合并数组
            const currentList = refresh ? [] : (this.data.noticeList || []);
            const mergedList = currentList.concat(newNotices);
            
            console.log('合并后的通知列表:', mergedList);
            
            this.setData({
              noticeList: mergedList,
              isLoading: false,
              hasMore: hasMore,
              page: this.data.page + 1
            });
          } else {
            console.error('获取通知失败:', res);
            this.setData({ 
              isLoading: false,
              errorMsg: (res.data && res.data.message) || '获取通知失败'
            });
            wx.showToast({
              title: '获取通知失败',
              icon: 'none'
            });
          }
          resolve();
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.setData({
            isLoading: false,
            hasMore: false,
            errorMsg: '网络连接失败，请检查网络'
          });
          wx.showToast({
            title: '网络连接失败',
            icon: 'none'
          });
          resolve();
        }
      });
    });
  },

  // 查看通知详情
  viewNoticeDetail: function(e) {
    const noticeId = e.currentTarget.dataset.id;
    console.log('查看通知详情:', noticeId);
    // 跳转到通知详情页面
    wx.navigateTo({
      url: `/pages/admin/notice/detail/detail?id=${noticeId}`
    });
  },
  
  // 编辑通知
  editNotice: function(e) {
    const noticeId = e.currentTarget.dataset.id;
    console.log('编辑通知:', noticeId);
    wx.navigateTo({
      url: `/pages/admin/notice/edit/edit?id=${noticeId}`
    });
  },
  
  // 删除通知
  deleteNotice: function(e) {
    const noticeId = e.currentTarget.dataset.id;
    console.log('准备删除通知:', noticeId);
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条通知吗？删除后无法恢复。',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.performDelete(noticeId);
        }
      }
    });
  },
  
  // 执行删除操作
  performDelete: function(noticeId) {
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.showLoading({
      title: '删除中...',
    });
    
    wx.request({
      url: `${serverUrl}/api/admin/notices/${noticeId}`,
      method: 'DELETE',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200 || res.statusCode === 204) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 从列表中移除已删除的通知
          const updatedList = this.data.noticeList.filter(item => item.id !== noticeId);
          this.setData({
            noticeList: updatedList
          });
        } else {
          wx.showToast({
            title: res.data.message || '删除失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '删除失败，请检查网络',
          icon: 'none'
        });
      }
    });
  },
  
  // 发布新通知
  sendNewNotice: function() {
    console.log('发布新通知');
    wx.navigateTo({
      url: '/pages/admin/notice/send/send'
    });
  },
  
  // 重试加载
  retryLoad: function() {
    console.log('重试加载通知');
    this.loadNoticeList(true);
  }
});